﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Web.Http.Cors;
using Ttifa.Infrastructure.Utils;

namespace Ttifa.WebApiBase.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
    public class AllowCorsAttribute : Attribute, ICorsPolicyProvider
    {
        private CorsPolicy _policy;

        public AllowCorsAttribute()
        {
            // Create a CORS policy.
            _policy = new CorsPolicy
            {
                AllowAnyHeader = true
            };

            //read config from web.config
            var origins = ConfigManager.GetSetting("Cors.Origins");
            if (origins == "*")
            {
                _policy.AllowAnyOrigin = true;
            }
            else
            {
                // Add allowed origins.
                var hosts = origins.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var host in hosts)
                {
                    _policy.Origins.Add(host);

                }
            }

            var methods = ConfigManager.GetSetting("Cors.Methods");
            if (methods == "*")
            {
                _policy.AllowAnyMethod = true;
            }
            else
            {
                var allMethods = methods.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var m in allMethods)
                {
                    _policy.Methods.Add(m);
                }
            }
        }

        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return Task.FromResult(_policy);
        }
    }
}
